import "./assets/styles/reset.css";
import "./assets/styles/flex.min.css";
import "./assets/styles/page.min.css";

import pkg from "../package.json";
import _ from "lodash";
import http from "./http";

import { setupProdMockServer } from "../lib";
import { handleCopy } from "./utils";

const { camelCase, upperFirst } = _;

const apis = setupProdMockServer();

function getApiName(item: any) {
  const { url, method } = item;
  return `${upperFirst(method)}${upperFirst(camelCase(url))}`;
}

function getMockData(method = "get", url = "") {
  // return new Promise((resolve, reject) => {
  //   resolve({ method, url, data: { name: "张三", age: 24, gender: "男" } });
  // });
  return http(method, url, {}).then((res: any) => ({ method, url, data: res }));
}

let activeLi: any = null;
let contStr = "";

function handleClick(ele: HTMLElement | null) {
  if (!ele) throw new Error(`不存在该元素`);
  ele.addEventListener("click", (e: any) => {
    const isAtLi = e.target.classList?.contains("item");
    if (!isAtLi) return;
    activeLi?.classList.remove("active");
    activeLi = e.target;
    activeLi.classList.add("active");
    const { method, url } = e.target.dataset;
    getMockData(method, url).then((res: any) => {
      contStr = JSON.stringify(res);
      document.querySelector("#cont")!.innerHTML = JSON.stringify(res, null, 4);
    });
  });
}

// 获取内容区域的字符串
function getContentHtml(apis: any) {
  console.log(apis, "apis-------------");
  const appName = pkg.name
    .split("-")
    .map((it) => it.charAt(0).toUpperCase() + it.slice(1))
    .join("-");
  const lis = apis
    .map(
      (it) =>
        `<li class="item f-fs-c" data-method="${it.method}" data-url="${
          it.url
        }">${getApiName(it)}</li>`
    )
    .join("");
  return `
<div class="layout f-sb-s">
  <div class="menu f-0 f-fs-s-c">
    <h1 class="h1 f-0 f-c-c">${appName}</h1>
    <ul class="navs" id="navs">
    ${lis}
    </ul>
  </div>
  <div class="main f-1 f-fs-s-c">
    <div class="btns-box f-fe-c f-0">
      <button class="btn f-c-c" id="copy">一键复制</button>
    </div>
    <pre class="cont f-1" id="cont">
    ~ 暂无内容 ~
    </pre>
  </div>
</div>
`;
}

/**
 * 将浏览器路径对象转为参数
 * @param {CommonObj} params 要转化的参数
 */
function urlParamsToSearch(params?: CommonObj) {
  if (!params) return "";
  let str: string = "";
  for (const key in params) {
    const val = params[key] ?? "";
    if (typeof val === "object")
      throw new Error("路由参数中不允许传入非基本数据类型的值");
    str += `&${key}=${val}`;
  }
  return str.slice(1);
}

/**
 * 将浏览器路径参数转为对象
 * @param {string} searchStr 要转化的字符串
 * @param {string[]} noHandleKeys 不需要处理（转number、布尔值等）的字符串
 */
export function urlSearchToParams(path: string, noHandleKeys?: string[]) {
  if (!path) return "";
  const str = path.split("?")[1];
  const obj: CommonObj = {};
  str.split("&").forEach((item: string) => {
    let [key, val] = item.split("=");
    if (!noHandleKeys?.includes(key) && val !== "") {
      const num = Number(val);
      if (!isNaN(num)) {
        val = num as any;
      } else {
        if (val === "true") {
          val = true as any;
        } else if (val === "false") {
          val = false as any;
        }
      }
    }
    obj[key] = val;
  });
  return obj;
}

const app = document.querySelector<HTMLDivElement>("#app");
app!.innerHTML = getContentHtml(apis);

handleClick(document.querySelector("#navs"));
const ind = (urlSearchToParams(location.search)?.id ?? 1) - 1;
document.querySelectorAll("#navs .item")?.[ind]?.click(); // 初始化选中第一个
document.querySelector("#copy")!.addEventListener("click", () => {
  handleCopy(contStr);
});
